﻿module Sustainalytics.Screening {

    import Common = Sustainalytics.Common;
    import LRTM = Sustainalytics.LRTM;

    export class FiltersController {

        //public editedFilter: FilterDto;
        public expandedFilter: string='';
        
        // list of filters
        public filtersList: FilterDto[];

        public systemAndFavFilters: FilterDto[];
        public otherFilters: FilterDto[];


        // specifies whether current controller is in loading state
        public isLoading: boolean;

        public strTargetType: string ='';
        public targetType: TargetType;
        public entityName: string;

        private accountId: string;
        private userId: string;
        public targetToolTipValue: string;
        //private $routeParams: any;
        public isAdmin: boolean; //shows whether the module is used in CI or AI

        //Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private RoutingService: Routing.IRoutingService,
            private FilterService: IFilterService,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private ClaimsAuthorizationService: Claims.IClaimsAuthorizationService,
            private $modal: Common.IModal) {

            var ctx = this;
            //ctx.$routeParams = ctx.RoutingService.getRouteParams();
            //var strTargetType = ctx.$routeParams['targetType'];

            ctx.isAdmin = $location.absUrl().indexOf('/admin/') > 0;

            //get accountId and userId to invalidate cache
            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }

            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            //new 
            //var strTargetType = '';
            if ($location.url() === '/tools/screening') {
                ctx.strTargetType = 'screening';
            } else if ($location.url() === '/tools/report') {
                ctx.strTargetType = 'report';
                ctx.targetToolTipValue = 'Report';
            }
            //new


            if (ctx.strTargetType === 'screening') {
                ctx.targetType = TargetType.Screening;
                ctx.entityName = 'filter';
                ctx.targetToolTipValue = 'Filter';
            }
            else if (ctx.strTargetType === 'report')
            {
                ctx.targetType = TargetType.Report;
                ctx.entityName = ctx.strTargetType;
            }

            if (!ctx.targetType) {
                if (ctx.ClaimsAuthorizationService.Validate("api/v1/screeningtool", "GET", [])) {
                ctx.$location.url('/tools/screening');
                } else if (ctx.ClaimsAuthorizationService.Validate("api/v1/datareportingtool", "GET", [])) {
                    ctx.$location.url('/tools/report');
                }
            }

            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId,
                'cookieDomain': 'none',
                'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: ctx.accountId,
                UserId: ctx.userId
            };
           
            var eventCategory = '';
            var eventAction = '';

            if (ctx.targetType == TargetType.Report) {
                eventCategory = 'Reporting tool';
                eventAction = 'ReportingToolLandingPage';
            }
            else {
                eventCategory = 'Screening tool';
                eventAction = 'ScreeningToolLandingPage';
            }

            ga('globalAccess.send', {
                'hitType': 'event',
                'eventCategory': eventCategory,
                'eventAction': eventAction,
                'eventLabel': JSON.stringify(gaObject)
            });

            ctx['sortableOptions_systemAndFavFilters'] = {
                stop: (event, ui) => {
                    if (!ctx.isAdmin) {
                        ctx.saveUserCustomFilterOrder(ctx.targetType, ScreenRegion.SystemAndFavFilters);
                    }
                }
            };

            ctx['sortableOptions_otherFilters'] = {
                cancel: ".unsortable",
                stop: (event, ui) => {
                    if (!ctx.isAdmin) {
                        ctx.saveUserCustomFilterOrder(ctx.targetType, ScreenRegion.OtherFilters);
                    }
                }
            };

            ctx.getUserFilters();
        }

        public tutorialPreview() {
            var ctx = this;

            var $modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/tutorial_dialog.tpl.html',
                    controller: 'TutorialController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        title: function () {
                            return "Screening Tool Overview";
                        },
                        url: function () {
                            return "http://www.sustainalytics.com/sites/default/files/uploads/2015-08-31-GAV5-ScreeningTool.mp4";
                        }

                    }

                });


        }

        public tutorialPreview2() {
            var ctx = this;

            var $modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/tutorial_dialog.tpl.html',
                    controller: 'TutorialController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        title: function () {
                            return "Report Generation Tool Overview";
                        },
                        url: function () {
                            return "http://www.sustainalytics.com/sites/default/files/uploads/2015-08-31-GAV4-ReportGenerationTool.mp4";
                        }

                    }

                });


        }

        public setExpandedFilter(filterId: string) {
            var ctx = this;
            ctx.expandedFilter = ctx.expandedFilter === filterId ?  '' : filterId;
        }

        public generateReport(filter: FilterDto)
        {
            var ctx = this;
            var taskNumber = filter.exportType == ExportType.Excel ? 100 : 101;
            var reportType = "";
            var filterMatrix = "";
            var filterComparativeGroup = "";

            var eventAction = "";

            if (filter.targetType === TargetType.Screening) {
                var screeningPromise = ctx.LongRunningTaskManagerService.runTask(filter.name + '_' + moment().format("DDMMYYYY"), filter.id, taskNumber, true, null);
                if (filter.type === FilterType.Standard) {
                    reportType = "Screening tool - system filters";
                    eventAction = ExportType[filter.exportType] + filter.name;
                } else {
                    reportType = "Screening tool - custom filters";
                    eventAction = ExportType[filter.exportType] + "CustomFilter";
                }
            }

            if (filter.targetType === TargetType.Report) {
                var reportPromise = ctx.LongRunningTaskManagerService.runTask(filter.name + '_' + moment().format("DDMMYYYY"), filter.id, taskNumber, true, null);
                if (filter.type === FilterType.Standard) {
                    reportType = "Reporting tool - system reports";
                    eventAction = ExportType[filter.exportType] + filter.name;
                } else {
                    reportType = "Reporting tool - custom reports";

                    eventAction = ExportType[filter.exportType] + "CustomReport";
                    filterMatrix = filter.weightMatrixName;
                    filterComparativeGroup = ComparativeGroupEnum[filter.comparativeGroup];
                }
            }

            if (reportType !== '') {
                ga('create', 'UA-4379897-6', {
                    'userId': ctx.userId,
                    'cookieDomain': 'none',
                    'name': 'globalAccess'
                });

                ga('globalAccess.set', 'dimension1', ctx.userId);

                var dateNow = new Date();
                var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                var gaObject: any = {
                    Date: dateNowString,
                    AccountId: ctx.accountId,
                    UserId: ctx.userId
                };

                if (reportType === "Reporting tool - custom reports") {
                    gaObject.Matrix = filterMatrix;

                    if (!isNaN(parseInt(filterComparativeGroup)))
                        filterComparativeGroup = ComparativeGroupEnum[filterComparativeGroup];

                    gaObject.ComparativeGroup = filterComparativeGroup;
                }

                ga('globalAccess.send', {
                    'hitType': 'event',
                    'eventCategory': reportType,
                    'eventAction': eventAction,
                    'eventLabel': JSON.stringify(gaObject)
                });
            }
        }

        public doEditAction(filter: FilterDto) {
            var ctx = this;

            if (filter.type !== FilterType.Standard)
            {
                ctx.$location.url('/tools/'+ctx.strTargetType+'/filters/' + filter.id);
            }
            else
            {
                if (ctx.isAdmin) {
                    //clone standard filter to <standard_filter_name> (new version)
                    filter.isSourceForClone = true;
                    filter.name = filter.name + " (new version)";
                    filter.targetType = ctx.targetType;
                    filter.status = FilterStatus.Draft;
                    filter.isFavorite = false;
                    filter.shared = false;
                    filter.publishDate = moment().toDate();

                    var promise = ctx.FilterService.saveFilter(filter);

                    promise.then((filter: FilterDto) => {
                        //redirect to details page to edit the clone
                        ctx.$location.url('/tools/'+ctx.strTargetType+'/filters/' + filter.id);
                    },
                        (reason) => {
                            ctx.notificationFactory.error('Error creating draft standard filter: ' + filter.name + '.', reason.data.message);
                        });
                } else {
                    ctx.$location.url('/tools/'+ctx.strTargetType+'/filters/' + filter.id);
                }
            }
        }

        public getUserFilters(): ng.IPromise<FilterDto[]> {

            var ctx = this;
            ctx.$rootScope['loading'] = true;

            var promise = ctx.FilterService.getUserFilters(ctx.targetType);
            promise.then((filters: FilterDto[]) => {
                ctx.filtersList = filters;

                ctx.systemAndFavFilters = ctx.filtersList.filter(function (item) {
                    return item.type === FilterType.Standard || item.isFavorite;
                });

                //display only standard filters when in admin
                if (ctx.isAdmin) {
                    ctx.systemAndFavFilters = ctx.filtersList.filter(function (item) {
                        return (item.type === FilterType.Standard);
                    });
                }

                ctx.otherFilters = ctx.filtersList.filter(function (item) {
                    return item.type !== FilterType.Standard && !item.isFavorite;
                });

                ctx.$rootScope['loading'] = false;
            },
                (reason) => {
                    ctx.notificationFactory.error('Error retrieving ' + ctx.entityName+'s.', reason.data.message);
                    ctx.$rootScope['loading'] = false;
            });

            return promise;
        }

        public saveUserCustomFilterOrder(targetType: TargetType, screenRegion: ScreenRegion) {
            var ctx = this;
            var filterIds: Array<string> = [];

            if (screenRegion === ScreenRegion.SystemAndFavFilters) {
                ctx.systemAndFavFilters.forEach((item: FilterDto) => {
                    filterIds.push(item.id);
                });
            }
            else if (screenRegion === ScreenRegion.OtherFilters) {
                ctx.otherFilters.forEach((item: FilterDto) => {
                    filterIds.push(item.id);
                });
            }

            ctx.FilterService.saveUserCustomFilterOrder(targetType, screenRegion, filterIds)
                .then(() => {
                ctx.notificationFactory.success(ctx.entityName + ' order updated successfully.');
            },
            (reason) => {
                ctx.notificationFactory.error('Error updating '+ctx.entityName+' order.', reason.data.message);
            });
        }


        public getNewEntityName(counter:number) {
            var ctx = this;
            var newEntityName = "new " + ctx.entityName + " (" + (counter) + ")";

            var found = ctx.filtersList.filter(function (item) {
                return item.name === newEntityName;
            });

            if (found.length > 0) {
                counter += 1;
                return ctx.getNewEntityName(counter);
            }
            else
            {
                return newEntityName;
            }
        }

        public getCloneName(name: string, counter:number) {
            var ctx = this;
            var cloneName = name + " (" + counter.toString() + ")";

            var found = ctx.filtersList.filter(function (item) {
                return item.name === cloneName;
            });

            if (found.length > 0) {
                counter += 1;
                return ctx.getCloneName(name, counter);
            }
            else {
                return cloneName;
            }
        }


        public createFilter() {

            var ctx = this;
            var filterName = ctx.getNewEntityName(ctx.filtersList.length + 1);

            var filterDto = new FilterDto();
            filterDto.name = filterName;
            filterDto.isFavorite = false;
            filterDto.type = FilterType.Private;
            filterDto.shared = false;
            filterDto.status = FilterStatus.Active;
            filterDto.targetType = ctx.targetType;
            filterDto.exportType = ExportType.Excel;

            var promise = ctx.FilterService.saveFilter(filterDto);

            promise.then((filter:FilterDto) => {
                //redirect to details page
                ctx.$location.url('/tools/'+ctx.strTargetType+'/filters/' + filter.id);
            },
                (reason) => {
                    ctx.notificationFactory.error('Error creating '+ctx.entityName+'.', reason.data.message);
            });
        }

        public shareFilter(filter: FilterDto, share: boolean) {
            var ctx = this;
            
            if (share)
            {
                filter.type = FilterType.Shared;
            }
            else
            {
                filter.type = FilterType.Private;
            }

            var promise = ctx.FilterService.saveFilter(filter);
            promise.then((filter: FilterDto) => {
                ctx.getUserFilters();
            },
                (reason) => {
                    ctx.notificationFactory.error('Error sharing '+ctx.entityName+'.', reason.data.message);
            });
        }

        public favouriteFilter(filter: FilterDto) {
            var ctx = this;
            
            filter.isFavorite = !filter.isFavorite;

            var promise = ctx.FilterService.saveFilter(filter);
            promise.then((filter: FilterDto) => {
                ctx.getUserFilters();
            },
                (reason) => {
                    ctx.notificationFactory.error('Error making '+ctx.entityName+' favourite.', reason.data.message);
            });
        }

        public cloneFilter(filter: FilterDto) {
            var ctx = this;

            var clone = new FilterDto();

            for (var prop in filter) {
                clone[prop] = filter[prop];
            }

            var cloneName = ctx.getCloneName(clone.name, 1);
            clone.isSourceForClone = true;
            clone.name = cloneName;
            clone.isFavorite = false;
            clone.type = FilterType.Private;
            clone.shared = false;
            clone.status = FilterStatus.Active;
            clone.targetType = ctx.targetType;

            var promise = ctx.FilterService.saveFilter(clone);
            promise.then((filter: FilterDto) => {
                ctx.getUserFilters();
            },
                (reason) => {
                    ctx.notificationFactory.error('Error cloning ' + ctx.entityName + '.', reason.data.message);
            });
        }

        public deleteFilter(filterId) {

            var ctx = this;

            var modalInstanceDelete = ctx.$modal.open({
                templateUrl: 'Views/Tools/ScreeningTool/confirmationDialog.tpl.html',
                controller: 'ConfirmationController',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    message: function () {
                        return "Are you sure you want to remove this " + ctx.entityName + " ?";
                    }
                }
            });

            modalInstanceDelete.result.then((out) => {
                if (out['confirmResult'] == true) {
                    ctx.$rootScope['loading'] = true;
                    var promise = ctx.FilterService.deleteFullFilter(filterId);
                    promise.then((data) => {
                        ctx.getUserFilters();
                    },
                        (reason: any) => {
                            ctx.notificationFactory.error('Error removing ' + ctx.entityName + '.', reason.data.message);
                        });
                }
            });
        }

    }

    angular.module(screeningToolModuleName).controller('FiltersController',
        ['$rootScope', '$scope', '$q', '$location', 'RoutingService', 'FilterService', 'LongRunningTaskManagerService', 'notificationFactory', 'staticObjects','ClaimsAuthorizationService', '$modal', FiltersController]);
}
